// @flow
import React, { Component } from 'react'
import styles from './Home.css'
import AgGrid from 'components/AgGrid'
import universalFetch, { handleFetchError } from 'store/modules/fetch'

type Props = {}
type States = {
  columnDefs: Array<Object>,
  pageSize: number,
  currentPage: number,
  totalSize: number,
  rowData: Array<any>
}
class Dict extends Component {
  props: Props
  state: States
  getData: Function
  onPageChange: Function

  constructor (props: Props) {
    super(props)
    this.state = {
      pageSize: 25,
      currentPage: 1,
      totalSize: 0,
      rowData: [],
      columnDefs: [
        {
          headerName: '名称',
          field: 'label',
          cellStyle: {
            padding: '8px'
          }
        },
        {
          headerName: '值',
          field: 'value',
          cellStyle: {
            padding: '8px'
          }
        },
        {
          headerName: '类型',
          field: 'type',
          cellStyle: {
            padding: '8px'
          }
        },
        {
          headerName: '扩展',
          field: 'ext',
          cellStyle: {
            padding: '8px'
          }
        }
      ]
    }

    this.getData = this.getData.bind(this)
    this.onPageChange = this.onPageChange.bind(this)
  }

  getData (page: number, pageSize: number) {
    universalFetch(`${__SERVICE_API__}sys/dicts?pageNum=${page}&pageSize=${pageSize}`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          currentPage: page,
          totalSize: json.pageInfo.total,
          rowData: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  onPageChange (page: number, pageSize: number) {
    this.getData(page, pageSize)
  }

  componentWillMount () {
    this.getData(1, this.state.pageSize)
  }

  render () {
    const { columnDefs, currentPage, totalSize, rowData, pageSize } = this.state
    return (
      <div className={styles['main']}>
        <AgGrid {...{
          columnDefs,
          pageSize: pageSize,
          onPageChange: this.onPageChange,
          currentPage: currentPage,
          totalSize: totalSize,
          rowData: rowData
        }} />
      </div>
    )
  }
}

export default Dict
